/**
 * 后期处理下数据
 */
var fs = require("fs");
var path = require("path");

function mkdir(dir) {
    var arr = dir.split("/");
    var p = "";
    for (var i in arr) {
        p += arr[i] + "/";
        if (!fs.existsSync(p)) fs.mkdirSync(p);
    }
}

function copy(src, dst) {
    if (!fs.existsSync(src)) {
        console.log("源文件不存在", src);
        return;
    }
    var dir = path.dirname(dst);
    if (!fs.existsSync(dir)) mkdir(dir);
    fs.writeFileSync(dst, fs.readFileSync(src));
}

function visit(dir, cb) {
    if (!fs.existsSync(dir)) {
        console.log("源文件不存在", dir);
        return;
    }
    fs.readdirSync(dir).forEach(function(file) {
        var p = dir + "/" + file;
        if (fs.statSync(p).isDirectory()) {
            visit(p, cb);
        }
        else {
            cb(p);
        }
    });
}

function copyDir(src, dst) {
    visit(src, function(p) {
        copy(p, dst + p.replace(src, ""));
    });
}

function deleteDir(dir) {
    var files = [];
    if (fs.existsSync(dir)) {
        files = fs.readdirSync(dir);
        files.forEach(function(file, index) {
            var currPath = dir + "/" + file;
            if (fs.statSync(currPath).isDirectory()) deleteDir(currPath);
            else fs.unlinkSync(currPath);
        });
        fs.rmdirSync(dir);
    }
}

function replaceFile(files, data) {
    for (var i in files) {
        var file = files[i];
        var content = fs.readFileSync(file).toString();
        for (var k in data) {
            content = content.replace(k, data[k]);
        }
        fs.writeFileSync(file, content);
    }
}

function copyFullDir(dst, url, tryUrl, extra) {
    copyDir("build/admin/", "build/" + dst + "/admin/");
    copyDir("build/js/", "build/" + dst + "/js/");
    copyDir("build/public/", "build/" + dst + "/public/");
    copyDir("build/js/", "build/" + dst + "/js/");
    
    replaceFile([ 
        "build/" + dst + "/public/all/js/context.js", 
        "build/" + dst + "/admin/js/admin.min.js",
        "build/" + dst + "/admin/js/login.min.js",
    ], 
    {
        "http://www.1hc8.com/" : url,
        "http://www.1hc8.com:9090/" : tryUrl,
    });
}

// 菠菜
console.log("* wechat...");
copyFullDir("bocai", "http://www.bocai8877.com/", "http://try.bocai8877.com/");
copyDir("build/wx", "build/bocai/wx");
copyDir("build/group", "build/bocai/group");
replaceFile([ "build/bocai/group/js/admin.min.js",
    "build/bocai/group/js/login.min.js", "build/bocai/wx/js/center.min.js" ], 
{
    "http://www.1hc8.com/" : "http://www.bocai8877.com/",
    "http://www.1hc8.com:9090/" : "http://try.bocai8877.com/",
});
replaceFile([ "build/bocai/admin/login.html", "build/bocai/admin/admin.html" ], 
{
    "// bocai = true;": "bocai = true;",
});
